package com.starrocks.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.starrocks.common.Result;
import com.starrocks.entity.SyncLogEntity;
import com.starrocks.service.SyncLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 同步日志控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/log")
public class SyncLogController {

    @Autowired
    private SyncLogService syncLogService;

    /**
     * 分页查询同步日志
     */
    @GetMapping("/list")
    public Result<IPage<SyncLogEntity>> list(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize,
            @RequestParam(required = false) Long configId,
            @RequestParam(required = false) String sourceTableName,
            @RequestParam(required = false) String targetTableName,
            @RequestParam(required = false) String syncType,
            @RequestParam(required = false) String syncStatus) {
        try {
            IPage<SyncLogEntity> page = syncLogService.pageList(
                pageNum, pageSize, configId, sourceTableName, targetTableName, syncType, syncStatus
            );
            return Result.success(page);
        } catch (Exception e) {
            log.error("查询同步日志失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询最近N条日志
     */
    @GetMapping("/recent")
    public Result<List<SyncLogEntity>> getRecentLogs(
            @RequestParam(defaultValue = "100") int limit) {
        try {
            List<SyncLogEntity> logs = syncLogService.getRecentLogs(limit);
            return Result.success(logs);
        } catch (Exception e) {
            log.error("查询最近日志失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询指定表的最新日志
     */
    @GetMapping("/latest")
    public Result<SyncLogEntity> getLatestLog(
            @RequestParam String sourceTableName,
            @RequestParam String targetTableName) {
        try {
            SyncLogEntity log = syncLogService.getLatestLog(sourceTableName, targetTableName);
            return Result.success(log);
        } catch (Exception e) {
            log.error("查询最新日志失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 清理指定天数之前的日志
     */
    @DeleteMapping("/clean")
    public Result<String> cleanOldLogs(@RequestParam(defaultValue = "30") int days) {
        try {
            int count = syncLogService.cleanOldLogs(days);
            return Result.success("已清理 " + count + " 条日志");
        } catch (Exception e) {
            log.error("清理日志失败", e);
            return Result.error("清理失败：" + e.getMessage());
        }
    }
}

